<?php
/**
 * Prado Portal.
 *
 * @author Steen Rabol <steen.rabol@gmail.com>
 * @link http://www.pradoportal.dk/
 * @copyright Copyright &copy; 2006,2007,2008 Steen Rabol
 * @license http://www.pradoportal.dk
 * @version $Id: ImportIPCountry.php 340 2010-01-30 22:44:10Z steen.rabol@gmail.com $
 *
 */

Prado::using('Application.Common.Data.PortalLanguageRecord');
Prado::using('Application.Common.Data.PortalLanguageStringRecord');

class ImportIPCountry extends PortalAdminPage
{
	private $_langid;

	public function onLoad($param)
	{
		$this->_langid		= TPropertyValue::ensureInteger($this->Request['langid']);

		parent::onLoad($param);

		$this->setAdminPageTitle('Import IP country');
		$this->FileUpload->setAttribute("size",30);

		if(!$this->IsPostBack)
		{
			$this->FileUpload->MaxFileSize	= PortalUtil::return_bytes(ini_get('upload_max_filesize'));
			$this->ltFileSize->Text			= ini_get('upload_max_filesize');
		}
	}

	public function onFileUpload($sender,$param)
	{
		if($sender->HasFile)
		{
			PortalUtil::CreateDirStructure($this->Application->PortalBasePath	. '/storage/tmp');

			$savepath	= $this->Application->PortalBasePath	. '/storage/tmp/' . $sender->FileName;
			$sender->saveAs($savepath);

			if(TPropertyValue::ensureInteger($this->DeleteFirst->Checked))
			{
				$sql = "delete from tblshortstat_iptocountry";
				try
				{
					$this->DbConnection->createCommand($sql)->execute();
				}
				catch(Exception $e)
				{
					$this->reportError(1,$e->getMessage());
				}
			}

			$handle = fopen($savepath, "r");
			$db = $this->Application->DbConnection;

			$sql = "INSERT INTO tblshortstat_iptocountry(ip_from,ip_to,country_code2,country_code3,country_name) VALUES";
			$i = 0;
			while (($data = fgetcsv($handle, 2048, ",")) !== FALSE)
			{
			    $ipfrom			= $data[0];
			    $ipto			= $data[1];
			    $countrycode2	= $db->quoteString($data[2]);
			    $countrycode3	= $db->quoteString($data[3]);
			    $country		= $db->quoteString($data[4]);

				$sql .= "($ipfrom,$ipto,$countrycode2,$countrycode3,$country),";
				if($i == 500)
				{
					$sql = substr($sql,0,-1);
					$db->createCommand($sql)->execute();
					$sql = "INSERT INTO tblshortstat_iptocountry(ip_from,ip_to,country_code2,country_code3,country_name) VALUES";
					$i=0;
				}

				$i++;
			}

			if($handle)
			{
				$sql = substr($sql,0,-1);
				$db->createCommand($sql)->execute();
			}

			fclose($handle);
			$this->gotoPage('Admin.Home');
		}
	}
}

?>